#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import inspect
import logging
import pkgutil
import re
import traceback

import pkg_resources
from packaging import version

import ylzagent
from ylzagent import config
from ylzagent.loggings import logger
from ylzagent.utils.comparator import operators
from ylzagent.utils.exception import VersionRuleException

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime

import requests
import base64
import json


def get_config():
    print(25255,)
    map = {
        "serviceName": config.agent_service_name,  # 是agent_name  #cloud_auth
        "cluster": config.agent_cluster         #cloud
    }
    print('map',map)
    url = "http://192.168.246.225:8080/admin/agent/getConfig/" + base64.b64encode(json.dumps(map).encode()).decode()

    response = requests.post(url)
    content = response.content.decode("utf-8")
    print('content1',content)
    content_data = json.loads(content)['data']
    print('content_data999',content_data)
    config.ignore_http_path_with_method = content_data.get("agent.tracing.ignore_endpoint","") #"GET:/system/dept/list,GET:/system/menu/list"
    config.ignore_http_host_with_port= content_data.get("agent.ip.limit","")          #"192.168.0.1-192.168.0.225,192.168.1.1-192.168.1.225"
    config.ignore_tracing_closeSelf = content_data.get("agent.tracing.closeSelf","").lower() != 'false'    #true/false
    # config.ignore_tracing_each = content_data.get("agent.ignore_tracing_each","") #'127.0.0.1/aaa/b'
    config.agent_login_request_parms = json.loads(content_data.get("login.request.params", '{}'))  # '127.0.0.1/aaa/b'
    print('config.agent_login_request_parms999',config.agent_login_request_parms,type(config.agent_login_request_parms))
    print("每1分钟执行",datetime.now())
    print('content',content)

    print('config.agent_login_request_parms',config.agent_login_request_parms)

scheduler = BackgroundScheduler()
scheduler.add_job(get_config, 'interval', minutes=1)
scheduler.start()

def install():
    disable_patterns = config.agent_disable_plugins
    if isinstance(disable_patterns, str):
        disable_patterns = [re.compile(p.strip()) for p in disable_patterns.split(',') if p.strip()]
    else:
        disable_patterns = [re.compile(p.strip()) for p in disable_patterns if p.strip()]
    for importer, modname, _ispkg in pkgutil.iter_modules(ylzagent.plugins.__path__):
        if any(pattern.match(modname) for pattern in disable_patterns):
            logger.info("plugin %s is disabled and thus won't be installed", modname)
            continue
        logger.debug('installing plugin %s', modname)
        plugin = importer.find_module(modname).load_module(modname)

        # todo: refactor the version checker, currently it doesn't really work as intended
        supported = pkg_version_check(plugin)
        if not supported:
            logger.debug("check version for plugin %s's corresponding package failed, thus "
                         "won't be installed", modname)
            continue

        if not hasattr(plugin, 'install') or inspect.ismethod(plugin.install):
            logger.warning("no `install` method in plugin %s, thus the plugin won't be installed", modname)
            continue

        # noinspection PyBroadException
        try:
            plugin.install()
            logger.debug('Successfully installed plugin %s', modname)
        except Exception:
            logger.warning(
                'Plugin %s failed to install, please ignore this warning '
                'if the package is not used in your application.',
                modname
            )
            traceback.print_exc() if logger.isEnabledFor(logging.DEBUG) else None


def pkg_version_check(plugin):
    supported = True

    # no version rules was set, no checks
    if not hasattr(plugin, 'version_rule'):
        return supported

    pkg_name = plugin.version_rule.get('name')
    rules = plugin.version_rule.get('rules')

    try:
        current_pkg_version = pkg_resources.get_distribution(pkg_name).version
    except pkg_resources.DistributionNotFound:
        # when failed to get the version, we consider it as supported.
        return supported

    current_version = version.parse(current_pkg_version)
    # pass one rule in rules (OR)
    for rule in rules:
        if rule.find(' ') == -1:
            if check(rule, current_version):
                return supported
        else:
            # have to pass all rule_uint in this rule (AND)
            rule_units = rule.split(' ')
            results = [check(unit, current_version) for unit in rule_units]
            if False in results:
                # check failed, try to check next rule
                continue
            else:
                return supported

    supported = False
    return supported


def check(rule_unit, current_version):
    idx = 2 if rule_unit[1] == '=' else 1
    symbol = rule_unit[0:idx]
    expect_pkg_version = rule_unit[idx:]

    expect_version = version.parse(expect_pkg_version)
    f = operators.get(symbol) or None
    if not f:
        raise VersionRuleException(f'version rule {rule_unit} error. only allow >,>=,==,<=,<,!= symbols')

    return f(current_version, expect_version)


def check_ip_in_range(ip, ip_ranges):  #ignore 用
    ip_parts = ip.split('.')
    ip_int = int(ip_parts[0]) * 256**3 + int(ip_parts[1]) * 256**2 + int(ip_parts[2]) * 256 + int(ip_parts[3])
    ip_ranges = ip_ranges.split(',')
    for ip_range in ip_ranges:
        if '-' in ip_range:
            start, end = ip_range.split('-')
            start_parts = start.split('.')
            end_parts = end.split('.')
            start_int = int(start_parts[0]) * 256**3 + int(start_parts[1]) * 256**2 + int(start_parts[2]) * 256 + int(start_parts[3])
            end_int = int(end_parts[0]) * 256**3 + int(end_parts[1]) * 256**2 + int(end_parts[2]) * 256 + int(end_parts[3])
            if start_int <= ip_int <= end_int:
                return True
        else:
            if ip == ip_range:
                return True
    return False

def ignore_http_request(host:str,path:str,method:str):
    # print(2828289,host,path)
    _host = host
    _path = path.split('?')[0]
    print(89898,_path)
    _method = method.upper()

    _ignore_http_path_with_method = config.ignore_http_path_with_method   # "GET:/system/dept/list,GET:/system/menu/list"
    if _ignore_http_path_with_method!='':
        conditions_path = list(map(lambda item: item.split(':'),_ignore_http_path_with_method.split(',')))
        for condition in conditions_path :
            if (condition[0].upper() == _method and condition[1] == _path):
                return True
    # localhost:8888
    _ignore_http_host_with_port = config.ignore_http_host_with_port
    if _ignore_http_host_with_port!='' and check_ip_in_range(_host,_ignore_http_host_with_port):
        return True

    _ignore_tracing_closeself = config.ignore_tracing_closeself
    _ignore_tracing_auto = config.ignore_tracing_auto


    if _ignore_tracing_closeself  and _ignore_tracing_auto!='':
        for each_path in _ignore_tracing_auto.split(','):
            try:
                each_path = each_path.split(':')[0].upper()+':'+each_path.split(':')[1]
            except:
                each_path = ''
            if method.upper() +':'+ path == each_path:
                return True

    return False

def tag_loggin_session(host:str,path:str,method:str,headers,cookies):   #request
    session=""
    username=""

    loginPath = config.agent_login_request_parms.get('loginPath','')
    sessionKey = config.agent_login_request_parms.get('sessionKey','')
    tokenPrefix = config.agent_login_request_parms.get('tokenPrefix','')
    loginParmasAuthKey = config.agent_login_request_parms.get('loginParmasAuthKey','')
    cookieSessionKey = config.agent_login_request_parms.get('cookieSessionKey','')
    cookieSessionUserKey = config.agent_login_request_parms.get('cookieSessionUserKey','')
    # loginpath符合
    try:
        loginPath = loginPath.split(':')[0].upper() + ':' + loginPath.split(':')[1]
    except:
        loginPath = ''
    if loginPath != method.upper() +":"+path:
        return None
    # headers
    headers_session = headers.get(sessionKey,'')
    if headers_session!='' and headers_session.startwith(tokenPrefix):   #去掉ba
        session = headers_session.replace(tokenPrefix,'')
        username = headers.get(loginParmasAuthKey,'')
        return {"session": session, "loginUser": username}
    # cookies
    cookies_session = headers.get(cookieSessionKey, '')
    if cookies_session !='':
        session = cookies_session
        username = cookies.get(cookieSessionUserKey, '')
        return {"session": session, "loginUser": username}
    return None

def tag_return_value(response):     #response
    responseTokenType = config.agent_login_request_parms.get('responseTokenType','')
    responseTokenKey = config.agent_login_request_parms.get('responseTokenKey','')

    # countReturn = config.agent_login_request_parms['countReturn']
    printReturnValue = config.agent_login_request_parms.get('printReturnValue','false')
    try:
        returnValueAllCollect = int(config.agent_login_request_parms.get('returnValueAllCollect','1'))
    except:
        returnValueAllCollect = 1
    # encryptDocument = config.agent_login_request_parms['lencryptDocument']
    print('responseTokenType',responseTokenType)
    print('responseTokenKey',responseTokenKey)
    print('printReturnValue',printReturnValue)
    print('returnValueAllCollect',returnValueAllCollect)
    if printReturnValue.lower() == 'false':

        return None

    if responseTokenType.upper() != 'JSON' or response.content_type.lower() != 'application/json':
        return None
    print('7775',type(response.data))

    content = response.data.decode("utf-8")
    print('content1', content)
    content_data = json.loads(content)
    print('88888',content_data)
    data = content_data.get(responseTokenKey,None)
    if data==None:
        data = response.data
    if data==None:
        return None
    if type(data)!=list:
        return str(data)

    return str(data[:returnValueAllCollect])

